package cn.yuanqiao.archive.bianjifabu.service.impl;

import cn.yuanqiao.activiti.service.RemoteActivitiService;
import cn.yuanqiao.archive.Identify.domain.TenantYqKfjdFolderDa;
import cn.yuanqiao.archive.Identify.domain.TenantYqKfjdJob;
import cn.yuanqiao.archive.Identify.domain.TenantYqKfjdJobDa;
import cn.yuanqiao.archive.appManager.domain.*;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantMdataListMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantSysDictDataMapper;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.appManager.service.impl.TenantMijiComparisonTableServiceImpl;
import cn.yuanqiao.archive.bianjifabu.domain.Yqfabufangan;
import cn.yuanqiao.archive.bianjifabu.domain.YqfabufanganDa;
import cn.yuanqiao.archive.bianjifabu.domain.Yqfanganwater;
import cn.yuanqiao.archive.bianjifabu.mapper.YqfabufanganMapper;
import cn.yuanqiao.archive.bianjifabu.service.IYqfabufanganService;
import cn.yuanqiao.archive.bianjifabu.util.PdfUtils;
import cn.yuanqiao.archive.chengguojieshou.mapper.YqdaarticulatedMapper;
import cn.yuanqiao.archive.management.utils.entity.Asip;
import cn.yuanqiao.archive.utils.FileWaterMark;
import cn.yuanqiao.archive.wenjianzhengli.mapper.TenantYqdaFolderMapper;

import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import org.apache.commons.io.FileUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import cn.yuanqiao.common.enums.DbIdEnum;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigInteger;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


/**
 * 发布方案Service业务层处理
 *
 * @author yuanqiao
 * @date 2024-03-18
 */
@Service
public class YqfabufanganServiceImpl implements IYqfabufanganService
{
    @Autowired
    private YqfabufanganMapper YqfabufanganMapper;
    @Autowired
    private RemoteActivitiService remoteActivitiService;
    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;
    @Autowired
    private ITenantSysConfigService sysConfigService;
    @Autowired
    private TenantMdataListMapper tenantMdataListMapper;
    @Autowired
    private TenantYqdaFolderMapper tenantYqdaFolderMapper;
    @Autowired
    private TenantSysDictDataMapper tenantSysDictDataMapper;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private YqdaarticulatedMapper yqdaarticulatedMapper;
    @Value("${FBswitch}")
    private Boolean FBswitch;
    @Autowired
    private TenantMijiComparisonTableServiceImpl mijiComparisonTableService;

    private String isDoc = "";
    private List<Yqfanganwater> listResultWater = new ArrayList<>();
    private String pathOfFile = "";
    private Map<String, Object> fondsMap = new HashMap<>();
    private List<TenantMdataList> juanMdataList = new ArrayList<>();
    private TenantCodeList tenantCodeList = null;
    private TenantCodeRule tenantCodeRule = null;
    private TenantMdataList tenantMdataList = null;
    private TenantSysDictData tenantSysDictData =  null;

    @Resource
    private SqlSessionFactory sqlSessionFactory;
    /**
     * 查询发布方案
     *
     * @param ID 发布方案主键
     * @return 发布方案
     */
    @Override
    public Yqfabufangan selectYqfabufanganByID(String ID)
    {
        Yqfabufangan yqfabufangan = YqfabufanganMapper.selectYqfabufanganByID(ID, new Yqfabufangan().getTableName());
        TenantCategory category = tenantCategoryMapper.selectTenantCategoryByTableName(yqfabufangan.getSubTableName(), new TenantCategory().getTableName());
        yqfabufangan.setCategoryId(category.getId());
        return yqfabufangan;
    }

    /**
     * 查询发布方案列表
     *
     * @param Yqfabufangan 发布方案
     * @return 发布方案
     */
    @Override
    public List<Yqfabufangan> selectYqfabufanganList(Yqfabufangan Yqfabufangan)
    {
        Date faburq = Yqfabufangan.getFaburq();
        Date faburq2 = Yqfabufangan.getFaburq2();
        if(faburq!=null){
            int i = faburq.compareTo(faburq2);
            if(i==0){
                faburq2.setHours(24);
            }
        }
        return YqfabufanganMapper.selectYqfabufanganList(Yqfabufangan);
    }

    @Override
    public List<YqfabufanganDa> selectDataOfFangan(String fanganId) {
        return YqfabufanganMapper.selectYqfabufanganDaByFanganId(fanganId,new YqfabufanganDa().getTableName());
    }

    @Override
    public List<Map<String, Object>> selectDaList(JSONObject jsonObject) {
        String fabuWangduan = jsonObject.getString("fabuWangduan");
        String fabuFangshi = jsonObject.getString("fabuFangshi");
        String subTableName = jsonObject.getString("subTableName");
        throwExcep(fabuWangduan,"fabuWangduan不能为空");
        throwExcep(fabuFangshi,"fabuFangshi不能为空");
        throwExcep(subTableName,"subTableName");
        Map<String,Object> map = jsonObject.toJavaObject(Map.class);
        if (FBswitch) {
            List<TenantRyMjDzb> getdamjbyrymj = mijiComparisonTableService.getdamjbyrymj();
            String tiaojian = " and MJ in ('" + getdamjbyrymj.stream().map(m->m.getDaMj()).collect(Collectors.joining("','")) +"') ";
            map.put("tiaojian",tiaojian);
        }
        List<Map<String, Object>> list = YqfabufanganMapper.selectDaList(map);
        return list;
    }

    @Override
    public List<Map<String, Object>> kfjdList(String subTableName) {
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByTableName(subTableName,new TenantCategory().getTableName());
        String subTableName2 = "";
        if(tenantCategory.getType()==0){
            subTableName2 = tenantCategory.getFileTableName();
        }
        if(tenantCategory.getType()==1){
            subTableName2 = tenantCategory.getFolderTableName();
        }
        if(tenantCategory.getType()==3){
            subTableName2 = tenantCategory.getItemTableName();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("subTableName",subTableName2);
        map.put("categoryName",tenantCategory.getName());
        map.put("tableName",new TenantYqKfjdJob().getTableName());
        map.put("type",tenantCategory.getType());
        map.put("jianTableName",new TenantYqKfjdJobDa().getTableName());
        map.put("folderTableName",new TenantYqKfjdFolderDa().getTableName());
        PageUtils.startPage();
        List<Map<String, Object>> list = YqfabufanganMapper.kfjdList(map);
        return list;
    }

    @Override
    public List<Map<String, Object>> showColumnsByCateID(String subTableName,String type) {
        throwExcep(subTableName,"subTableName不能为空");
        throwExcep(type,"type不能为空");
        TenantCategory tenantCategory = new TenantCategory();
        TenantCategory tenantCategory1 = tenantCategoryMapper.selectTenantCategoryByTableName(subTableName, tenantCategory.getTableName());
        PageUtils.startPage();
        List<Map<String, Object>> list = YqfabufanganMapper.showColumnsByCateID(new TenantMdataList().getTableName(),
                tenantCategory.getTableName(), tenantCategory1.getId(),type);
        return list;
    }

    @Override
    public List<Map<String, Object>> getFileList(String fanganId,String subTableName) {
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByTableName(subTableName, new TenantCategory().getTableName());
        PageUtils.startPage();
        List<Map<String, Object>> list = YqfabufanganMapper.getFileList(tenantCategory.getEfileTableName(),new YqfabufanganDa().getTableName(),fanganId);
        return list;
    }

    @Override
    public int addDaToFangan(JSONObject jsonObject) {
        String fanganId = jsonObject.getString("fanganId");
        String subTableName = jsonObject.getString("subTableName");
        String categoryName = jsonObject.getString("categoryName");
        JSONArray jsonArray = jsonObject.getJSONArray("ids");
        if(jsonArray==null || jsonArray.size()==0){
            throw new ServiceException("档案id不能为空");
        }
        throwExcep(fanganId,"方案id不能为空");
        throwExcep(subTableName,"subTableName不能为空");
        throwExcep(categoryName,"categoryName不能为空");
        //查询已经加到方案里面的档案id
        List<Map<String, Object>> idMap = YqfabufanganMapper.selectDaIdByFanganId(fanganId, new YqfabufanganDa().getTableName());
        List<String> list = new ArrayList<>();
        List<String> list1 = jsonArray.toJavaList(String.class);
        if(null!=idMap){
            idMap.stream().forEach(m-> list.add(String.valueOf(m.get("DA_ID"))));
            //排除已经加到方案里面的档案id
            if(list.size()!=0){
                for(int i=0;i<list1.size();i++){
                    if(list.contains(list1.get(i))){
                        list1.remove(i);
                        i--;
                    }
                }
            }
        }
        if(list1==null || list1.size()<=0){
            return 999;
        }
        YqfabufanganDa yqfabufanganDa = new YqfabufanganDa();
        yqfabufanganDa.setFanganId(fanganId);
        yqfabufanganDa.setCategoryName(categoryName);
        yqfabufanganDa.setState("0");
        int t = 0;
        for(int j=0;j<list1.size();j++){
            List<Map<String, Object>> list2 = YqfabufanganMapper.selectDaById(list1.get(j),subTableName);
            Map<String, Object> map = list2.get(0);
            yqfabufanganDa.setDaId(String.valueOf(map.get("ID")));
            yqfabufanganDa.setDh(String.valueOf(map.get("DH")));
            yqfabufanganDa.setZrz(String.valueOf(map.get("ZRZ")));
            yqfabufanganDa.setTitle(String.valueOf(map.get("TITLE")));
            yqfabufanganDa.setRq(String.valueOf(map.get("RQ")));
            yqfabufanganDa.setYs(String.valueOf(map.get("YS")));
            yqfabufanganDa.setIsOpens(String.valueOf(map.get("IS_OPENS")));
            yqfabufanganDa.setBz(String.valueOf(map.get("BZ")));
            t = YqfabufanganMapper.insertYqfabufanganDa(yqfabufanganDa);
        }
        return t;
    }

    @Override
    public int addJianDingJobDa(JSONObject jsonObject) {
        String subTableName = jsonObject.getString("subTableName");
        JSONArray ids = jsonObject.getJSONArray("ids");
        String fanganId = jsonObject.getString("fanganId");
        if(ids==null || ids.size()==0){
            throw new ServiceException("鉴定任务ids不能为空");
        }
        throwExcep(subTableName,"subTableName不能为空");
        throwExcep(fanganId,"fanganId");
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByTableName(subTableName, new TenantCategory().getTableName());
        Integer type = tenantCategory.getType();
        List<Map<String, Object>> list = YqfabufanganMapper.selectDaIdByFanganId(fanganId, new YqfabufanganDa().getTableName());
        Map<String, Object> map = new HashMap<>();
        map.put("type",type);
        map.put("jianTableName",new TenantYqKfjdJobDa().getTableName());
        map.put("juanTableName",new TenantYqKfjdFolderDa().getTableName());
        List<String> list1 = ids.toJavaList(String.class);
        map.put("daIdList",list1);
        List<Map<String, Object>> list2 = YqfabufanganMapper.selectDaOfKfjdJob(map);

        YqfabufanganDa yqfabufanganDa = new YqfabufanganDa();
        yqfabufanganDa.setFanganId(fanganId);
        yqfabufanganDa.setCategoryName(tenantCategory.getName());
        yqfabufanganDa.setState("0");
        int t=0;
        if(list!=null && list.size()!=0){
            List<String> list3 = new ArrayList<>();
            list.stream().forEach(m-> list3.add(String.valueOf(m.get("DA_ID"))));
            for(int k=0;k<list2.size();k++){
                Map<String, Object> map1 = list2.get(k);
                String daid = String.valueOf(map1.get("DAID"));
                if(list3.contains(daid)){
                    list2.remove(k);
                    k--;
                }
            }
            for(int j=0;j<list2.size();j++){
                Map<String, Object> map1 = list2.get(j);
                String daid = String.valueOf(map1.get("DAID"));
                List<Map<String, Object>> list4 = YqfabufanganMapper.selectDaById(daid, subTableName);
                Map<String, Object> map2 = list4.get(0);
                yqfabufanganDa.setDaId(String.valueOf(map2.get("ID")));
                yqfabufanganDa.setDh(String.valueOf(map2.get("DH")));
                yqfabufanganDa.setZrz(String.valueOf(map2.get("ZRZ")));
                yqfabufanganDa.setTitle(String.valueOf(map2.get("TITLE")));
                yqfabufanganDa.setRq(String.valueOf(map2.get("RQ")));
                yqfabufanganDa.setYs(String.valueOf(map2.get("YS")));
                yqfabufanganDa.setIsOpens(String.valueOf(map2.get("IS_OPENS")));
                yqfabufanganDa.setBz(String.valueOf(map2.get("BZ")));
                t = YqfabufanganMapper.insertYqfabufanganDa(yqfabufanganDa);
            }
            if(list2!=null && list2.size()==0){
                t=1;
            }

        }else{
            if(list2!=null && list2.size()!=0){
                for(int i=0;i<list2.size();i++){
                    Map<String, Object> map1 = list2.get(i);
                    String daid = String.valueOf(map1.get("DAID"));
                    List<Map<String, Object>> list3 = YqfabufanganMapper.selectDaById(daid, subTableName);
                    Map<String, Object> map2 = list3.get(0);
                    yqfabufanganDa.setDaId(String.valueOf(map2.get("ID")));
                    yqfabufanganDa.setDh(String.valueOf(map2.get("DH")));
                    yqfabufanganDa.setZrz(String.valueOf(map2.get("ZRZ")));
                    yqfabufanganDa.setTitle(String.valueOf(map2.get("TITLE")));
                    yqfabufanganDa.setRq(String.valueOf(map2.get("RQ")));
                    yqfabufanganDa.setYs(String.valueOf(map2.get("YS")));
                    yqfabufanganDa.setIsOpens(String.valueOf(map2.get("IS_OPENS")));
                    yqfabufanganDa.setBz(String.valueOf(map2.get("BZ")));
                    t = YqfabufanganMapper.insertYqfabufanganDa(yqfabufanganDa);
                }
            }
        }

        return t;
    }

    @Override
    public int addAllDaToFangan(JSONObject jsonObject) {
        String fabuWangduan = jsonObject.getString("fabuWangduan");
        String fabuFangshi = jsonObject.getString("fabuFangshi");
        String fanganId = jsonObject.getString("fanganId");
        String subTableName = jsonObject.getString("subTableName");
        String categoryName = jsonObject.getString("categoryName");
        throwExcep(fanganId,"方案id不能为空");
        throwExcep(subTableName,"subTableName不能为空");
        throwExcep(categoryName,"categoryName不能为空");
        throwExcep(fabuWangduan,"fabuWangduan不能为空");
        throwExcep(fabuFangshi,"fabuFangshi不能为空");
        Map<String,Object> map = jsonObject.toJavaObject(Map.class);
        //要批量添加的所有档案
        List<Map<String, Object>> list2 = YqfabufanganMapper.selectDaList(map);
        //查询已经加到方案里面的档案id
        List<Map<String, Object>> idMap = YqfabufanganMapper.selectDaIdByFanganId(fanganId, new YqfabufanganDa().getTableName());
        List<String> list = new ArrayList<>();
        if(null!=idMap){
            idMap.stream().forEach(m-> list.add(String.valueOf(m.get("DA_ID"))));
            if(list.size()!=0){
                for(int i=0;i<list2.size();i++){
                    Map<String, Object> map1 = list2.get(i);
                    if(list.contains(String.valueOf(map1.get("ID")))){
                        list2.remove(i);
                        i--;
                    }
                }
            }
        }
        YqfabufanganDa yqfabufanganDa = new YqfabufanganDa();
        yqfabufanganDa.setFanganId(fanganId);
        yqfabufanganDa.setCategoryName(categoryName);
        yqfabufanganDa.setState("0");
        int t = 0;
        for(int j=0;j<list2.size();j++){
            Map<String, Object> map1 = list2.get(j);
            yqfabufanganDa.setDaId(String.valueOf(map1.get("ID")));
            yqfabufanganDa.setDh(String.valueOf(map1.get("DH")));
            yqfabufanganDa.setZrz(String.valueOf(map1.get("ZRZ")));
            yqfabufanganDa.setTitle(String.valueOf(map1.get("TITLE")));
            yqfabufanganDa.setRq(String.valueOf(map1.get("RQ")));
            yqfabufanganDa.setYs(String.valueOf(map1.get("YS")));
            yqfabufanganDa.setIsOpens(String.valueOf(map1.get("IS_OPENS")));
            yqfabufanganDa.setBz(String.valueOf(map1.get("BZ")));
            t = YqfabufanganMapper.insertYqfabufanganDa(yqfabufanganDa);
        }
        if(list2!=null && list2.size()==0){
            t = 1;
        }
        return t;
    }
    public void throwExcep(String field,String msg){
        if(StringUtils.isEmpty(field) || "null".equals(field)){
            throw new ServiceException(msg);
        }
    }
    /**
     * 新增发布方案
     *
     * @param Yqfabufangan 发布方案
     * @return 结果
     */
    @Override
    public int insertYqfabufangan(Yqfabufangan Yqfabufangan)
    {
        String fabuFangshi = Yqfabufangan.getFabuFangshi();
        String fabuWangduan = Yqfabufangan.getFabuWangduan();
        if("2".equals(fabuFangshi) && ("2".equals(fabuWangduan) || "3".equals(fabuWangduan))){
            throw new ServiceException("只有局域网可以在线发布");
        }
        if("1".equals(fabuFangshi) && "1".equals(fabuWangduan)){
            throw new ServiceException("局域网禁止离线发布");
        }
        Yqfabufangan.setCreateTime(DateUtils.getNowDate());
        Yqfabufangan.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getUserId()));
        Yqfabufangan.setCreator(SecurityUtils.getLoginUser().getSysUser().getNickName());
        Yqfabufangan.setState("-2");
        Yqfabufangan.setFabuState("0");
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(Yqfabufangan.getCategoryId(), new TenantCategory().getTableName());
        Yqfabufangan.setSubTableName(tenantCategory.getFileTableName());
        return YqfabufanganMapper.insertYqfabufangan(Yqfabufangan);
    }

    /**
     * 修改发布方案
     *
     * @param Yqfabufangan 发布方案
     * @return 结果
     */
    @Override
    public int updateYqfabufangan(Yqfabufangan Yqfabufangan)
    {
        Yqfabufangan.setLastUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getSysUser().getUserId()));
        Yqfabufangan.setLastUpdateTime(DateUtils.getNowDate());
        Yqfabufangan.setLastUpdater(String.valueOf(SecurityUtils.getLoginUser().getSysUser().getNickName()));
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(Yqfabufangan.getCategoryId(), new TenantCategory().getTableName());
        Yqfabufangan.setSubTableName(tenantCategory.getFileTableName());
        Yqfabufangan yqfabufangan = YqfabufanganMapper.selectYqfabufanganByID(Yqfabufangan.getId().toString(), Yqfabufangan.getTableName());
        if(!tenantCategory.getFileTableName().equals(yqfabufangan.getSubTableName())){
            String tenantCode = SecurityUtils.getTenantCode();
            yqdaarticulatedMapper.executeSql("delete from "+tenantCode+"_YQFABUFANGAN_DA where fangan_id = "+Yqfabufangan.getId());
        }
        return YqfabufanganMapper.updateYqfabufangan(Yqfabufangan);
    }

    /**
     * 批量删除发布方案
     *
     * @param
     * @return 结果
     */
    @Override
    public int deleteYqfabufanganByIDs(String ID,String fanganId)
    {
        return YqfabufanganMapper.deleteYqfabufanganByIDs(new YqfabufanganDa().getTableName(),ID,fanganId);
    }

    @Override
    public int updateState(String fanganId, String state) {
        Yqfabufangan yqfabufangan = new Yqfabufangan();
        yqfabufangan.setId(Long.valueOf(fanganId));
        yqfabufangan.setState(state);
        int i = YqfabufanganMapper.updateYqfabufangan(yqfabufangan);
        return i;
    }

    @Override
    public int submitBjfb(String fanganId) {
        List<Map<String, Object>> list = YqfabufanganMapper.selectYqfabufanganDaByFanganId2(fanganId, new YqfabufanganDa().getTableName());
        if(list==null || list.size()==0){
            throw new ServiceException("未添加档案不可发起审批");
        }
        //Yqfabufangan yqfabufangan = new Yqfabufangan();
        Yqfabufangan yqfabufangan1 = new Yqfabufangan();
        yqfabufangan1.setShenqingTime(DateUtils.getNowDate());
        yqfabufangan1.setState("0");
        yqfabufangan1.setId(Long.valueOf(fanganId));
        int i = YqfabufanganMapper.updateYqfabufangan(yqfabufangan1);


        Yqfabufangan yqfabufangan = YqfabufanganMapper.selectYqfabufanganByID(fanganId, new Yqfabufangan().getTableName());
        //时间处理
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 设置时区为上海
        // 使用SimpleDateFormat对象将Date对象格式化为字符串
        String formattedDate = sdf.format(yqfabufangan.getShenqingTime());

        Map<String,Object> variables = new HashMap<>();
        //档案数据  不传，审批过程中单独调接口查询档案数据
        variables.put("archiveData",list);
        Map<String, Object> map = yqfabufangan.toProcessMap();
        map.put("shenqingTime",formattedDate);
        //补充申请人和归属部门
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        Long deptId = SecurityUtils.getLoginUser().getSysUser().getDept().getDeptId();
        map.put("submitUserId",userId);
        map.put("submitDeptId",deptId);
        variables.put("processVariables",map);
        //发起流程
        remoteActivitiService.startProcessBjfb(variables);

        //variables.put("archive_has_mj","1");
        //variables.put("archive_is_dept","1");
        //variables.put("archive_site_view","1");
        //variables.put("archive_type","lt");

        return i;
    }

    @Override
    public File downLoadXml(JSONObject jsonObject) {
        JSONArray ids = jsonObject.getJSONArray("ids");
        String subTableName = jsonObject.getString("subTableName");
        String fabuType = jsonObject.getString("fabuType");
        String fanganId = jsonObject.getString("fanganId");
        if(ids==null || ids.size()==0){
            throw new ServiceException("ids不能为空");
        }
        throwExcep(subTableName,"subTableName不能为空");
        throwExcep(fabuType,"fabuType不能为空");
        throwExcep(fanganId,"fanganId不能为空");
        //发布成功与否都保存字段信息
        Yqfabufangan yqfabufangan1 = new Yqfabufangan();
        yqfabufangan1.setId(Long.valueOf(fanganId));
        //yqfabufangan1.setEfileFieldIds(JSON.toJSONString(efileFieldIds));
        yqfabufangan1.setFileFieldIds(JSON.toJSONString(ids));
        YqfabufanganMapper.updateYqfabufangan(yqfabufangan1);

        List<Map<String, Object>> list = YqfabufanganMapper.selectDaIdByFanganId(fanganId, new YqfabufanganDa().getTableName());
        if(null==list || list.size()==0){
            throw new ServiceException("不存在档案，无法打包！");
        }
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByTableName(subTableName,new TenantCategory().getTableName());
        //Long categoryId = tenantCategory.getId();
        //打包逻辑 start
        Map<String,Object> map = new HashMap<>();
        List<String> list1 = ids.toJavaList(String.class);
        map.put("fieldIds",list1);
        map.put("isDoc",fabuType);
        map.put("fanganId",fanganId);
        String path = "";
        try {
            path = packegMainUseByPubDownLoad(tenantCategory, list, map,tenantCategory.getEfileTableName());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //打包逻辑 end
        Yqfabufangan yqfabufangan = new Yqfabufangan();
        yqfabufangan.setFaburen(SecurityUtils.getLoginUser().getSysUser().getNickName());
        yqfabufangan.setFaburenId(String.valueOf(SecurityUtils.getLoginUser().getSysUser().getUserId()));
        yqfabufangan.setFaburq(DateUtils.getNowDate());
        yqfabufangan.setFabuState("1");
        yqfabufangan.setId(Long.valueOf(fanganId));
        YqfabufanganMapper.updateYqfabufangan(yqfabufangan);
        return new File(path);
    }
    public String[] getIpAndPort(String b) {
        //String b = "http://192.168.2.139:8080/dss";
        Pattern p = Pattern.compile("(\\d+\\.\\d+\\.\\d+\\.\\d+)\\:(\\d+)");
        Matcher m = p.matcher(b);
        String[] arr = new String[2];
        //将符合规则的提取出来
        while(m.find()) {
            //System.out.println("ip:"+m.group(1));
            //System.out.println("port:"+m.group(2));
            arr[0] = m.group(1);
            arr[1] = m.group(2);
        }
        return arr;
    }
    public boolean isReachable(String ipAddress, int port) {
        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(ipAddress, port), 3000); // 超时时间为5秒
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    @Override
    public void publishOnLine(JSONObject jsonObject) {
        String databaseId = sqlSessionFactory.getConfiguration().getDatabaseId();
        String fanganId = jsonObject.getString("fanganId");
        Yqfabufangan yqfabufangan1 = new Yqfabufangan();
        Yqfabufangan yqfabufangan2 = YqfabufanganMapper.selectYqfabufanganByID(fanganId, yqfabufangan1.getTableName());
        String fabuState = yqfabufangan2.getFabuState();
        if("1".equals(fabuState)){
            throw new ServiceException("已发布不可重复发布");
        }

        String fabuType = jsonObject.getString("fabuType");
        String subTableName = jsonObject.getString("subTableName");
        JSONArray fileFieldIds = jsonObject.getJSONArray("fileFieldIds");
        JSONArray efileFieldIds = jsonObject.getJSONArray("efileFieldIds");
        throwExcep(fanganId,"fanganId不能为空");
        throwExcep(fabuType,"fabuType不能为空");
        throwExcep(subTableName,"subTableName不能为空");
        //发布成功与否都保存字段信息
        yqfabufangan1.setId(Long.valueOf(fanganId));
        yqfabufangan1.setEfileFieldIds(JSON.toJSONString(efileFieldIds));
        yqfabufangan1.setFileFieldIds(JSON.toJSONString(fileFieldIds));
        YqfabufanganMapper.updateYqfabufangan(yqfabufangan1);

        TenantYqda tenantYqda = new TenantYqda();
        String bjfbonlineurl = sysConfigService.selectConfigByKey("BJFBONLINEURL");
        throwExcep(bjfbonlineurl,"发送地址参数BJFBONLINEURL未配置");
        String[] ipAndPort = getIpAndPort(bjfbonlineurl);
        boolean reachable = isReachable(ipAndPort[0],Integer.valueOf(ipAndPort[1]));
        if(!reachable){
            throw new ServiceException("发送地址参数BJFBONLINEURL配置有误");
        }
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByTableName(subTableName, new TenantCategory().getTableName());

        String fileColumn = "";
        String efileColumn = "";
        Long groupId = tenantCategory.getGroupId();
        TenantMdataList tenantMdataList = new TenantMdataList();
        tenantMdataList.setGroupId(groupId);
        if(fileFieldIds==null || fileFieldIds.size()==0){
            //演示先写死字段
            if(databaseId.equalsIgnoreCase(DbIdEnum.HIGHGO.getCode())){
              fileColumn = "COALESCE(IS_BORROW,'0') AS IS_BORROW,COALESCE(IS_ENTITY,'0') AS IS_ENTITY ,(case when EFILE_COUNT>0 then 1 else 0 end) as is_efile ,ID as DA_ID," +
                      "YS,BZ,GDCS,BGQX,TYPE,RQ,JH,ND,TITLE,GDSJ,QZH,MJ,IS_OPENS,IS_DEL AS ISDELETE,'7' as STATE,ZRZ,DH,0 AS DA_BOX_MARK,QZH as DAQZH,'"+tenantCategory.getFileTableName()+"' as sub_table_name";
            }else{
                fileColumn = "NVL(IS_BORROW,'0') AS IS_BORROW,NVL(IS_ENTITY,'0') AS IS_ENTITY ,(case when EFILE_COUNT>0 then 1 else 0 end) as is_efile ,ID as DA_ID," +
                        "YS,BZ,GDCS,BGQX,TYPE,RQ,JH,ND,TITLE,GDSJ,QZH,MJ,IS_OPENS,IS_DEL AS ISDELETE,'7' as STATE,ZRZ,DH,0 AS DA_BOX_MARK,QZH as DAQZH,'"+tenantCategory.getFileTableName()+"' as sub_table_name";
            }
//            tenantMdataList.setType(0);
//            List<TenantMdataList> lists = tenantMdataListMapper.selectTenantMdataListList(tenantMdataList);
//            List<String> fieldNames = new ArrayList<>();
//            lists.stream().forEach(str->{
//                fieldNames.add(str.getFieldName());
//            });
//            if(fieldNames.size()!=0){
//                fileColumn = String.join(",", fieldNames);
//            }
        }else{
            List<String> list3 = fileFieldIds.toJavaList(String.class);
            fileColumn = String.join(",", list3);
        }
        if("2".equals(fabuType)){  //目录+原文
            if(efileFieldIds==null || efileFieldIds.size()==0){
                //演示先写死字段
                efileColumn = "is_del,is_index,con_table_id,real_doc_name,type,path,action_time,doc_id,doc_order,doc_name," +
                        "doc_file_type,doc_file_size,'"+tenantCategory.getFileTableName()+"' as con_table_name,doc_mnt";
//                tenantMdataList.setType(2);
//                List<TenantMdataList> lists = tenantMdataListMapper.selectTenantMdataListList(tenantMdataList);
//                List<String> fieldNames = new ArrayList<>();
//                lists.stream().forEach(str->{
//                    fieldNames.add(str.getFieldName());
//                });
//                if(fieldNames.size()!=0){
//                    efileColumn = String.join(",", fieldNames);
//                }
            }else{
                List<String> list3 = efileFieldIds.toJavaList(String.class);
                //YqfabufanganMapper.getMdataListByIds(tenantMdataList.getTableName(), list3);
                efileColumn = String.join(",", list3);
            }
        }

        YqfabufanganDa yqfabufanganDa = new YqfabufanganDa();
        //1000条数据一批
        Integer num = 10;
        //该方案总共有多少条数据
        int totalNum = YqfabufanganMapper.countDaOfFangan(fanganId, yqfabufanganDa.getTableName());
        //一共多少批
        int totelBatchNo = Integer.valueOf(totalNum)/num+1;
        String fileTableName = tenantCategory.getFileTableName();
        String efileTableName = tenantCategory.getEfileTableName();
        System.out.println("方案id：：："+fanganId+"，一共分为"+totelBatchNo+"批");
        boolean isSuccess = true;
        List<String> idList = new ArrayList<>();
        for(int i=0;i<totelBatchNo;i++){
            List<Map<String, Object>> list = YqfabufanganMapper.selectDaByNum(fanganId, yqfabufanganDa.getTableName(), num.toString());
            list.stream().forEach(m-> idList.add(String.valueOf(m.get("DA_ID"))));

            List<Map<String, Object>> list1 = YqfabufanganMapper.selectFileDataByColumns(idList, fileTableName, fileColumn);
            String fileString = JSONArray.toJSONString(list1);
            String efileString = null;
            List<File> fileList = new ArrayList<>();
            if("2".equals(fabuType)){  //目录+原文
                List<Map<String, Object>> list2 = YqfabufanganMapper.selectEFileDataByColumns(idList, efileTableName, efileColumn);
                for(int k=0;k<list2.size();k++){
                    Map<String, Object> map1 = list2.get(k);
                    String docMnt = String.valueOf(map1.get("DOC_MNT"));
                    String path = String.valueOf(map1.get("PATH"));
                    File file = new File(docMnt + path);
                    if(file.exists()){
                        fileList.add(file);
                    }
                }
                efileString = JSONArray.toJSONString(list2);
            }

            String returnMsg = doPublish(bjfbonlineurl, fileString,efileString,fileList);
            JSONObject object = JSONObject.parseObject(returnMsg);
            String code = object.getString("code");
            //如果失败
            if("500".equals(code)){
                isSuccess = false;
                //部分数据发送成功 后更新部分状态 通过返回值返回的id
                JSONArray ids = object.getJSONArray("ids");
                if(ids!=null && ids.size()!=0){
                    List<String> list2 = ids.toJavaList(String.class);
                    updateState(list2,fileTableName,tenantYqda.getTableName(),yqfabufanganDa.getTableName(),fanganId,"1","1");
                }
                break;
            }
            //如果成功
            if("200".equals(code)){
                // 更新全部状态
                updateState(idList,fileTableName,tenantYqda.getTableName(),yqfabufanganDa.getTableName(),fanganId,"1","1");
            }
            idList.clear();
        }
        if(isSuccess) {
            Yqfabufangan yqfabufangan = new Yqfabufangan();
            yqfabufangan.setFaburen(SecurityUtils.getLoginUser().getSysUser().getNickName());
            yqfabufangan.setFaburenId(String.valueOf(SecurityUtils.getLoginUser().getSysUser().getUserId()));
            yqfabufangan.setFaburq(DateUtils.getNowDate());
            yqfabufangan.setFabuState("1");
            yqfabufangan.setId(Long.valueOf(fanganId));
            //yqfabufangan.setEfileFieldIds(JSON.toJSONString(efileFieldIds));
            //yqfabufangan.setFileFieldIds(JSON.toJSONString(fileFieldIds));
            YqfabufanganMapper.updateYqfabufangan(yqfabufangan);
        }else{
            throw new ServiceException("发布失败");
        }

    }

    @Override
    public int cancelPublish(String fanganId, String subTableName) {
        throwExcep(fanganId,"fanganId不能为空");
        throwExcep(subTableName,"subTableName不能为空");
        Yqfabufangan yqfabufangan = new Yqfabufangan();
        Yqfabufangan yqfabufangan1 = YqfabufanganMapper.selectYqfabufanganByID(fanganId, yqfabufangan.getTableName());
        String fabuFangshi = yqfabufangan1.getFabuFangshi();
        if("1".equals(fabuFangshi)){
            yqfabufangan.setFabuState("0");
            yqfabufangan.setId(Long.valueOf(fanganId));
            YqfabufanganMapper.updateYqfabufangan(yqfabufangan);
            return 1;
        }
        String bjfbonlineurl = sysConfigService.selectConfigByKey("BJFBONLINECANCELURL");
        throwExcep(bjfbonlineurl,"发送地址参数BJFBONLINECANCELURL未配置");
        String[] ipAndPort = getIpAndPort(bjfbonlineurl);
        boolean reachable = isReachable(ipAndPort[0],Integer.valueOf(ipAndPort[1]));
        if(!reachable){
            throw new ServiceException("发送地址参数BJFBONLINECANCELURL配置有误");
        }


        TenantYqda tenantYqda = new TenantYqda();
        YqfabufanganDa yqfabufanganDa = new YqfabufanganDa();
        String fabuWangduan = yqfabufangan1.getFabuWangduan();
        String fabuType = yqfabufangan1.getFabuType();
        String mubiaoXitong = yqfabufangan1.getMubiaoXitong();
        String code = "200";
        //List<String> updateIds = new ArrayList<>();
        List<String> idList = new ArrayList<>();
        if("1".equals(fabuWangduan) && mubiaoXitong.contains("阅览室")){
            List<Map<String, Object>> list = YqfabufanganMapper.selectDaIdByFanganId(fanganId, yqfabufanganDa.getTableName());
            list.stream().forEach(m-> idList.add(String.valueOf(m.get("DA_ID"))));
            Map<String,Object> map = new HashMap<>();
            map.put("ids",idList);
            map.put("fabuType",fabuType);
            map.put("type","cancel");

            String returnMsg = doCancel(bjfbonlineurl,map);
            JSONObject object = JSONObject.parseObject(returnMsg);
            code = object.getString("code");
            //JSONArray ids = object.getJSONArray("ids");
            //updateIds = ids.toJavaList(String.class);
        }

        if("200".equals(code)){
            //Yqfabufangan yqfabufangan = new Yqfabufangan();
            yqfabufangan.setFabuState("0");
            yqfabufangan.setId(Long.valueOf(fanganId));
            YqfabufanganMapper.updateYqfabufangan(yqfabufangan);
            if("1".equals(fabuWangduan) && mubiaoXitong.contains("阅览室")){
                updateState(idList,subTableName,tenantYqda.getTableName(),yqfabufanganDa.getTableName(),fanganId,"0","0");
            }
        }
        if("500".equals(code)){
            throw new ServiceException("撤销失败");
        }
        return "200".equals(code)?1:0;

    }

    /**
     * @param map
     * @return
     */
    public String doCancel(String url,Map<String,Object> map){
        MultiValueMap<String, Object> formData = new LinkedMultiValueMap<>();

        formData.add("cancelString", JSONObject.toJSONString(map)); // 添加其他数据

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        // 发送请求
        ResponseEntity<String> response = restTemplate.exchange(
                url, // 目标URL
                HttpMethod.POST,
                new HttpEntity<>(formData, headers),
                String.class
        );

        // 处理响应
        String body = response.getBody();
        System.out.println(body);
        return body;
    }

    @Transactional
    public void updateState(List<String> idList,String fileTableName,String yqdaTableName,
                            String fanganDaTableName,String fanganId,String bjfb,String state){
        YqfabufanganMapper.updateBjfbState(idList,fileTableName,"ID",bjfb);
        YqfabufanganMapper.updateBjfbState(idList,yqdaTableName,"DA_ID",bjfb);
        YqfabufanganMapper.updateFanganDaState(idList,fanganDaTableName,fanganId,state);
    }

    /**
     * @param fileString
     * @param efileString
     * @param fileList
     * @return
     */
    public String doPublish(String url,String fileString,String efileString,List<File> fileList){
        // 创建RestTemplate实例
        //RestTemplate restTemplate = new RestTemplate();

        // 准备文件
        //File file = new File("path/to/your/file.txt");
        //FileSystemResource fileResource = new FileSystemResource(file);

        // 创建MultiValueMap来存储表单数据
        MultiValueMap<String, Object> formData = new LinkedMultiValueMap<>();
        if(StringUtils.isNotEmpty(fileString)){
            formData.add("fileString", fileString); // 添加其他数据
        }
        if(StringUtils.isNotEmpty(efileString)){
            formData.add("efileString", efileString); // 添加其他数据
        }
        if(fileList!=null && fileList.size()!=0){
            for(int i=0;i<fileList.size();i++){
                FileSystemResource fileResource = new FileSystemResource(fileList.get(i));
                formData.add("files", fileResource); // 添加文件
            }
        }

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        // 发送请求
        ResponseEntity<String> response = restTemplate.exchange(
                url, // 目标URL
                HttpMethod.POST,
                new HttpEntity<>(formData, headers),
                String.class
        );

        // 处理响应
        String body = response.getBody();
        System.out.println(body);
        return body;
    }

    public synchronized String packegMainUseByPubDownLoad(TenantCategory category, List<Map<String,Object>> ids,
                                                          Map<String, Object> tagMap,String efileTableName) throws Exception {
        tenantCodeList = new TenantCodeList();
        tenantCodeRule = new TenantCodeRule();
        tenantMdataList = new TenantMdataList();
        //fabuwaterfontposition = sysConfigService.selectConfigByKey("FABUWATERFONTPOSITION");

        tenantSysDictData =  new TenantSysDictData();
        isDoc = String.valueOf(tagMap.get("isDoc"));
        String fanganId = String.valueOf(tagMap.get("fanganId"));
        Yqfanganwater yqfanganwater = new Yqfanganwater();
        yqfanganwater.setFanganId(fanganId);
        listResultWater = YqfabufanganMapper.selectYqfanganwaterList(yqfanganwater);

        List<String> daIdList = new ArrayList<>();
        ids.stream().forEach(m-> daIdList.add(String.valueOf(m.get("DA_ID"))));
        // 计算卷内件文件大小
        String sumFileSize = "0";
        sumFileSize = YqfabufanganMapper.sumFileSize(efileTableName, daIdList);
        //String EEPPath = SystemConfig.getParamValueByCode("HDDA_EEP_PATH") + "/" + new Date().getTime() + "";
        String EEPPath = sysConfigService.selectConfigByKey("BJFB_LX_PATH");
        throwExcep(EEPPath,"离线包临时路径BJFB_LX_PATH未配置！");
        EEPPath = EEPPath.endsWith("/")?EEPPath+System.currentTimeMillis():EEPPath+"/"+System.currentTimeMillis();
        pathOfFile = EEPPath;
        //String[] split = ids.split(",");
        File eepFile = new File(EEPPath);
        if (!eepFile.exists()) {
            eepFile.mkdirs();
        }
        fondsMap = new HashMap<>();
        List<Map<String, Object>> fonds = YqfabufanganMapper.getFondsAndDeptName(SecurityUtils.getTenantCode());
        for (Map<String, Object> m : fonds) {
            fondsMap.put(m.get("FONDS_CODE").toString(), m.get("ROLE_NAME"));
        }
        if(category.getType()==1){
            TenantMdataList tenantMdataList = new TenantMdataList();
            tenantMdataList.setGroupId(category.getGroupId());
            tenantMdataList.setIsExport(1);
            tenantMdataList.setType(1);
            juanMdataList = tenantMdataListMapper.selectTenantMdataListList(tenantMdataList);
        }
        for (int i = 0; i < daIdList.size(); i++) {
            this.getEEPPackeg2(category, daIdList.get(i), "", "f", EEPPath, tagMap,sumFileSize);
        }
        ZipUtils.zip(EEPPath,EEPPath);
        return EEPPath + ".zip";
    }

    public void outputXml(Document doc, String filename) {
        OutputFormat format = OutputFormat.createPrettyPrint();
        String paramValueByCode = sysConfigService.selectConfigByKey("HD_OUT_ZIP_FILE_CHARSET");
        paramValueByCode= StringUtils.isEmpty(paramValueByCode)?"GBK":paramValueByCode;
//		format.setEncoding("GBK");
        format.setEncoding(paramValueByCode);
        //解决自动闭合问题
        format.setExpandEmptyElements(true);
        XMLWriter writer;
        try {
            writer = new XMLWriter(new FileWriter(new File(filename)), format);
            writer.write(doc);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getEEPPackeg2(TenantCategory category, String ids, String path, String type, String storePath, Map<String, Object> tagMap,
                                String sumFileSize) throws Exception {
        try {
            List<TenantMdataList> mdataList = new ArrayList<>();
            List<Map<String, Object>> dhList = null;

            HashMap<String,String> hashMap = new HashMap<>();
            HashMap<String,String> hashMap2 = new HashMap<>();
            //卷内件的话添加卷层的信息
            if(category.getType()==1) {
                TenantYqdaFolder tenantYqdaFolder = tenantYqdaFolderMapper.selectByDaId(Long.valueOf(ids), new TenantYqdaFolder().getTableName());
                String folderIdStr = String.valueOf(tenantYqdaFolder.getFolderId());
                String string2 = String.valueOf(tenantYqdaFolder.getDaId());
                hashMap.put(string2, folderIdStr);
                if(!StringUtils.isEmpty(folderIdStr)) {
                    //List<Map<String, Object>> daMaps = DbTool.getListResult("SELECT folder_id as id,* FROM hdfolder WHERE folder_ID =" + folderIdStr + "");
                    List<Map<String, Object>> folderData = YqfabufanganMapper.getFolderData(category.getFolderTableName(), folderIdStr);
                    //查询档号
                    dhList = YqfabufanganMapper.getDhList(category.getId().toString(), category.getGroupId().toString(),
                            tenantCodeList.getTableName(), tenantCodeRule.getTableName(), tenantMdataList.getTableName());
                    for (Map<String, Object> daMap : folderData) {
                        String xml = getEEPXml(category, daMap, "v", juanMdataList, dhList);
                        String id = String.valueOf(daMap.get("ID"));
                        String dh = String.valueOf(daMap.get("DH"));
                        hashMap2.put(id, dh);
                        if(xml.contains("&"))xml=xml.replace("&", "&amp;");
                        Document document = DocumentHelper.parseText(xml);
                        //File f = new File(path + "/" + daMap.get("DH"));
                        File file = new File(storePath + "/" + daMap.get("DH"));
                        if(!file.exists()) {
                            file.mkdirs();
                        }
                        outputXml(document, storePath + "/" + daMap.get("DH") +"/"+daMap.get("DH") + ".xml");
                    }
                }
            }
            List<String> fieldIds = (List<String>) tagMap.get("fieldIds");
            mdataList = YqfabufanganMapper.getMdataListByIds(tenantMdataList.getTableName(), fieldIds);
            //mdataList = DbTool
            //        .getListResult("SELECT ID,FIELD_CAPTION,FIELD_NAME,SHOWTYPE FROM HDDAMDATALIST WHERE ID in ("+tagMap.get("fieldIds")+")");
            List<Map<String, Object>> daMaps = new ArrayList<>();
            if(!StringUtils.isEmpty(ids)) {
                daMaps = YqfabufanganMapper.getFolderData(category.getFileTableName(),ids);
            }
            if(dhList!=null) {
                dhList = null;
            }
            for (Map<String, Object> daMap : daMaps) {
                if(1==category.getType()) {
                    String da_id = String.valueOf(daMap.get("ID"));
                    String dh = hashMap2.get(hashMap.get(da_id));
                    daMap.put("AJDH", dh);
                    String xml = getEEPXml(category, daMap, type, mdataList, dhList);
                    if(xml.contains("&"))xml=xml.replace("&", "&amp;");
                    Document document = DocumentHelper.parseText(xml);

                    File file = new File(storePath + "/" + dh + "/" + daMap.get("DH"));
                    if(!file.exists()) {
                        file.mkdirs();
                    }
                    outputXml(document, storePath + "/" + dh+"/"+daMap.get("DH") +"/"+daMap.get("DH") + ".xml");

                }else {
                    String xml = getEEPXml(category, daMap, type, mdataList, dhList);
                    if(xml.contains("&"))xml=xml.replace("&", "&amp;");
                    Document document = DocumentHelper.parseText(xml);

                    File file = new File(storePath + "/"+ daMap.get("DH"));
                    if(!file.exists()) {
                        file.mkdirs();
                    }
                    outputXml(document, storePath + "/" +daMap.get("DH") +"/"+daMap.get("DH") + ".xml");
                }
            }
            // 添加文件说明eep start

            if (null != storePath) {
                Asip asip = new Asip();
                // 信息包唯一标识,后期如有信息包表可用来存储
                asip.setM1(UUID.randomUUID().toString().replaceAll("-", ""));
                asip.setM2("zip");
                asip.setM3("");
                asip.setM4(DateUtils.getTime());
                asip.setM5("");
                asip.setM6(storePath);
                asip.setM7("无");
                asip.setM490(sumFileSize == null ? "0" : sumFileSize);
                XStream xStream = new XStream(new DomDriver());
                xStream.processAnnotations(Asip.class);
                OutputStream os = null;
                os = new FileOutputStream(storePath + "/" + "说明文件.xml");
                xStream.toXML(asip, os);
                os.flush();
                os.close();
            }


        } catch (Exception e) {
            throw e;
        }
        return path;
    }

    public String getEEPXml(TenantCategory tenantCategory, Map<String, Object> daMap, String type,
                            List<TenantMdataList> mdataList, List<Map<String, Object>> dhList) throws Exception {
        String xml = "<?xml version=\"1.0\" encoding=\"GBK\"?>\r\n" + "<电子档案封装包\r\n"
                + "	xmlns=\"http://www.saac.gov.cn/standards/ERM/encapsulation\"\r\n"
                + "	xmlns:xsi=\" http://www.w3.org/2001/XMLSchema-instance\"\r\n";
                //+ "	xsi:schemaLocation=\"http://www.saac.gov.cn/standards/ERM/encapsulation eep.xsd\">\r\n";
        xml+= "	xsi:schemaLocation=\"http://www.saac.gov.cn/standards/ERM/encapsulation \">\r\n";
        xml+= "	<封装包格式描述>根据中华人民共和国档案行业标准DA/T 48-2009《基于XML的电子文件封装规范》生成</封装包格式描述>\r\n" + "	<版本>2009</版本>\r\n";
        xml+= "	<被签名对象 版本=\"2009\">\r\n" + "";
        String eepType = "原始型";
        // 封装包类型分为 原始型和修改型
        // 暂定原始型
        xml += "<封装包类型>" + eepType + "</封装包类型>";
        String eepRemark = "本封装包包含电子档案数据及其元数据，原始封装，未经修改";

        // 封装包类型描述分为
        // 本封装包包含电子文件数据及其元数据，原始封装，未经修改
        // 本封装包包含电子文件数据及其元数据，系修改封装，在保留原封装包的基础上，添加了修改层
        xml += "<封装包类型描述>" + eepRemark + "</封装包类型描述>";
        xml += "<封装包创建时间>" + DateUtils.getTime() + "</封装包创建时间>";
        xml += "<封装包创建单位></封装包创建单位>";
        xml += "<封装内容>";

        xml += getEEPDocumnets(tenantCategory, daMap, type, mdataList, dhList);


        xml += getBusiness(daMap.get("ID").toString(), "");
        xml += "</封装内容>";
        xml += "</被签名对象>";

        // 数字签名非必选,暂时预留
        // 缺一个何时调用数字签名和是否需要调用
        // xml += getDigitalSignature();
        xml += "</电子档案封装包>";
        return xml;
    }

    public String getBusiness(String daId, String type)  {
        String xml = "<业务实体块>";

        List<Map<String, Object>> businessActivity = YqfabufanganMapper.getBusinessActivity(SecurityUtils.getTenantCode() + "_BUSINESSACTIVITY", daId);
        for(int i=0;i<businessActivity.size();i++){
            Map<String, Object> map = businessActivity.get(i);
            xml += "<业务实体>";
            xml += "<业务标识符>"+map.get("ID")+"</业务标识符>";
            xml += "<机构人员标识符>"+map.get("USER_NAME")+"</机构人员标识符>";
            xml += "<文件标识符></文件标识符>";
            xml += "<业务状态></业务状态>";
            xml += "<业务行为>"+map.get("NAME")+"</业务行为>";
            xml += "<行为时间>"+map.get("ACTION_TIME")+"</行为时间>";
            xml += "<行为依据></行为依据>";

            xml += "<行为描述></行为描述>";
            xml += "</业务实体>";
        }
        //}
        xml += "</业务实体块>";
        return xml;
    }
    public String getEEPDocumnets(TenantCategory tenantCategory, Map<String, Object> daMap, String type,
                                  List<TenantMdataList> mdataList, List<Map<String, Object>> dhList) throws Exception {
        String xml = "<档案实体块>";
        xml += "<档案实体>";

        String jhcc = "文件";
        if ("f".equals(type)) {
        } else {
            jhcc = "案卷";
        }
        xml += "<聚合层次>" + jhcc + "</聚合层次>";
        xml += "<来源>";
        String lddw = "";
        if (daMap.get("QZH") != null) {
            if (fondsMap.containsKey(daMap.get("QZH").toString())) {
                lddw = (String) fondsMap.get(daMap.get("QZH").toString());
                if("null".equals(lddw) || StringUtils.isEmpty(lddw))
                    lddw = "";
             }
        }
        xml += "<立档单位名称>" + lddw + "</立档单位名称>";
        xml += "</来源>";
        xml += "<电子档案号>" + daMap.get("ID") + "</电子档案号>";

        // 档号先空闲
        xml += "<档号>";
        String s = "f".equals(type) ? "0" : "1";
        if("f".equals(type)) {
            //ArrayList singleListBySql = DbTool.getSingleListBySql("select id,TEMPLATE_ID from hddacategory where filetablename = (select sub_table_name from hdda where da_id = "+daMap.get("ID")+")");
            dhList = YqfabufanganMapper.getDhList(tenantCategory.getId().toString(), tenantCategory.getGroupId().toString(), tenantCodeList.getTableName(),
                    tenantCodeRule.getTableName(), tenantMdataList.getTableName());
        }
        for (Map<String, Object> dh : dhList) {
            if (dh.get("TYPE").toString().equals(s)) {
                String nodeValue = String.valueOf(daMap.get(dh.get("NODE_VALUE")));
                //TODO  处理内容含有< >问题，
                nodeValue=nodeValue.replace("<", "&lt;").replace(">", "&gt;");
                if("null".equals(nodeValue) || StringUtils.isEmpty(nodeValue)){
                    nodeValue = "";
                }
                xml += "<" + dh.get("FIELD_CAPTION") + ">" + nodeValue + "</"
                        + dh.get("FIELD_CAPTION") + ">";
            }
        }

        xml += "</档号>";

        // 内容描述先空闲
        xml += "<内容描述>";
        for (TenantMdataList tenantMdataList : mdataList) {
            // 如果有字典项，需要数据中的字典码值转换成行业通用的数据值，如本系统中秘密字典项值是30，但是在打包时需要设置成“秘密”而不是30
            // SHOWTYPE=5表示下拉，即字典取值
            if ("5".equals(String.valueOf(tenantMdataList.getShowType()))) {
                String dictName = tenantSysDictDataMapper.selectDictLabel(tenantMdataList.getFieldName(), String.valueOf(daMap.get(tenantMdataList.getFieldName())), tenantSysDictData.getTableName());
                if("null".equals(dictName) || StringUtils.isEmpty(dictName)) dictName = "";
                xml += "<" + tenantMdataList.getFieldCaption() + ">" + dictName + "</" + tenantMdataList.getFieldCaption() + ">";
            } else {
                //if("机构（问题）".equals(tenantMdataList.getFieldCaption())){
                //    continue;
                //}
                String fieldCaption = tenantMdataList.getFieldCaption();
                fieldCaption = fieldCaption.replace("（","").replace("）","")
                    .replace("(","").replace(")","");
                String object = String.valueOf(daMap.get(tenantMdataList.getFieldName()));
                object=object.replace("<", "&lt;").replace(">", "&gt;");
                if("null".equals(object) || StringUtils.isEmpty(object)) object = "";
                xml += "<" + fieldCaption + ">" +object + "</"
                        + fieldCaption + ">";
            }
        }
        xml += "</内容描述>";

        xml += "<形式特征>";
        // 目前系统中都是单件,没有组合文件
        xml += "<文件组合类型>单件</文件组合类型>";
        xml += "</形式特征>";

        xml += "<存储位置>";
        xml += "<脱机载体编号></脱机载体编号>";
        xml += "</存储位置>";
        xml += "<权限管理></权限管理>";

        String tableName = tenantCategory.getFileTableName();
        String efileTableName = tenantCategory.getEfileTableName();
        //tableName = DbTool.getSingle("select sub_table_name from hdda where da_id = "+daMap.get("ID"));
        if("2".equals(isDoc)) {
            if(tenantCategory.getType()==1) {
                xml += getFileList(efileTableName,tableName, daMap.get("ID").toString(),daMap.get("AJDH")+"/"+daMap.get("DH").toString());
            }else {
                xml += getFileList(efileTableName,tableName, daMap.get("ID").toString(),daMap.get("DH").toString());
            }
        }
        xml += "</档案实体>";
        xml += "</档案实体块>";
        return xml;
    }

    public String getFileList(String etableName,String tableName, String daId,String dh) throws Exception {
        String xml = "<文件数据>";
        List<Map<String, Object>> docData = YqfabufanganMapper.getDocData(etableName, daId, tableName);
        //List<Map<String, Object>> documents = DbTool.getListResult("SELECT * FROM HDDADOCUMENT WHERE IS_DEL=0 AND "
        //        + "CON_TABLE_ID='" + daId + "' AND CON_TABLE_NAME='" + tableName + "' ORDER BY DOC_ORDER");

        File file;
        for (Map<String, Object> document : docData) {
            file = new File(document.get("DOC_MNT")+ "" + document.get("PATH"));
            // 如果文件不存在，跳过当前记录
            if (!file.exists()) {
                continue;
            }
            String type = document.get("TYPE").toString();

            String t = "正文";
            if ("1".equals(type)) {
                t = "正文";
            } else if ("2".equals(type)) {
                t = "文稿";
            } else if ("3".equals(type)) {
                t = "报批件";
            } else {
                t = "附件";
            }
            xml += "<文档>";
            xml += "<文档标识符>" + document.get("DOC_ID") + "</文档标识符>";
            xml += "<文档主从声明>" + t + "</文档主从声明>";
            xml += "<文档数据>";
            xml += "<编码>";
            xml += "<电子属性>";
            xml += "<格式信息>" + document.get("DOC_FILE_TYPE") + "</格式信息>";
            xml += "<计算机文件名>" + document.get("DOC_NAME") + "</计算机文件名>";
            //xml += "<计算机真实文件名>" + document.get("DOC_NAME") + "</计算机文件名>";
            xml += "<计算机文件大小>" + document.get("DOC_FILE_SIZE") + "</计算机文件大小>";
            if ("正文".equals(t)) {
                // File file2 = new File(StaticData.HD_MNT+"/"+document.get("PATH"));
                xml += "<电子摘要>" + fileToMD5(document.get("DOC_MNT") +""+ document.get("PATH")) + "</电子摘要>";
            }
            xml += "<文档创建程序>档案管理系统</文档创建程序>";
            xml += "</电子属性>";

            String filePath = pathOfFile +"/"+dh+ "/File";
            File file3 = new File(filePath);
            if(!file3.exists()) {
                file3.mkdirs();
            }
            String newPath = "";
            String path = String.valueOf(document.get("PATH"));
            String docMnt = String.valueOf(document.get("DOC_MNT"));
            String[] pathArr = path.split("\\.");
            if("pdf".equalsIgnoreCase(pathArr[1])) {
                Boolean aBoolean = FileWaterMark.PdfIsEncryption(docMnt+path);
                if(!aBoolean){
                    String waterPath = pathArr[0]+"-fabuwater."+pathArr[1];
                    if(listResultWater.size()!=0) {
                        PdfUtils.PDFAddWatermark(docMnt+path, docMnt+waterPath, listResultWater.get(0));
                        newPath =  docMnt + waterPath;
                    }else {
                        newPath =  docMnt + document.get("PATH");
                    }
                }else{
                    newPath =  docMnt + document.get("PATH");
                }
            }else {
                newPath =  docMnt + document.get("PATH");
            }
            File file2 = new File(newPath);
            if(file2.exists()) {
                File destFile = new File(filePath+"/"+document.get("DOC_NAME"));
                FileUtils.copyFile(file2, destFile);
                String extension = getExtension(file2);
                if("pdf".equalsIgnoreCase(extension)) {
                    String fileNameWithoutExtension = getFileNameWithoutExtension(file2);
                    String newName = fileNameWithoutExtension+"-fabuwater."+extension;
                    File file4 = new File(newName);
                    if(file4.exists() && file4.isFile()) {
                        file4.delete();
                    }
                }


            }
            xml += "</编码>";
            xml += "</文档数据>";
            xml += "</文档>";
        }

        xml += "</文件数据>";
        return xml;
    }
    public String getFileNameWithoutExtension(File file) {
        String name = file.getName();
        int lastIndexOf = name.lastIndexOf('.');
        if (lastIndexOf > 0) {
            return name.substring(0, lastIndexOf);
        } else {
            return name;
        }
    }
    public String getExtension(File file) {
        String fileName = file.getName();
        int dotIndex = fileName.lastIndexOf('.');
        String extension = "";
        if (dotIndex != -1) {
            extension = fileName.substring(dotIndex + 1);
        }
        return extension;
    }
    public String fileToMD5(String source) {
        File file = new File(source);
        byte[] fileBytes = File2byte(file);
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        byte[] digest = md5.digest(fileBytes);
        return new BigInteger(1, digest).toString();
    }

    public static byte[] File2byte(File tradeFile) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(tradeFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }
    /**
     * 删除发布方案信息
     *
     * @param ID 发布方案主键
     * @return 结果
     */
    @Override
    public int deleteYqfabufanganByID(String ID)
    {
        return YqfabufanganMapper.deleteYqfabufanganByID(ID);
    }

    @Override
    public List<Yqfanganwater> selectYqfanganwaterList(String fanganId) {
        Yqfanganwater yqfanganwater = new Yqfanganwater();
        yqfanganwater.setFanganId(fanganId);
        List<Yqfanganwater> yqfanganwaters = YqfabufanganMapper.selectYqfanganwaterList(yqfanganwater);
        return yqfanganwaters;
    }

    @Override
    public int insertYqfanganwater(Yqfanganwater Yqfanganwater) {
        String fanganId = Yqfanganwater.getFanganId();
        throwExcep(fanganId,"fanganId不能为空");
        Yqfanganwater yqfanganwater2 = new Yqfanganwater();
        yqfanganwater2.setFanganId(fanganId);
        List<Yqfanganwater> yqfanganwaters = YqfabufanganMapper.selectYqfanganwaterList(yqfanganwater2);
        if(yqfanganwaters==null || yqfanganwaters.size()==0){
            return YqfabufanganMapper.insertYqfanganwater(Yqfanganwater);
        }else{
            return YqfabufanganMapper.updateYqfanganwater(Yqfanganwater);
        }
    }

}
